package com.baomidou.mybatisplus.samples.dytablename.interceptor;

import com.baomidou.mybatisplus.extension.plugins.handler.TableNameHandler;
import com.baomidou.mybatisplus.extension.plugins.inner.DynamicTableNameInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Random;

/**
 * @author xuguang
 */
@Configuration
public class InterceptorConfig {

    /**
     * 某种意义上对分表的支持（不是分库），只能说"图一乐"吧，可能涉及到老系统迁移的时候，会用到..
     *
     * @return 拦截器
     */
    @Bean
    public DynamicTableNameInnerInterceptor userDynamicTableNameInnerInterceptor() {
        DynamicTableNameInnerInterceptor dynamicTableNameInnerInterceptor = new DynamicTableNameInnerInterceptor();
        HashMap<String, TableNameHandler> map = new HashMap<String, TableNameHandler>(2) {{
            put("user", (sql, tableName) -> {
                String year = "_2018";
                int random = new Random().nextInt(10);
                if (random % 2 == 1) {
                    year = "_2019";
                }
                return tableName + year;
            });
        }};
        dynamicTableNameInnerInterceptor.setTableNameHandlerMap(map);
        return dynamicTableNameInnerInterceptor;
    }


    @Bean
    public MyInnerInterceptor myInnerInterceptor() {
        return new MyInnerInterceptor();
    }
}
